package cn.edu.bit.ss;



import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.edu.bit.ss.dao.BaseDAO;
import cn.edu.bit.ss.util.Queue;


public class SpiderMan {

	private Queue<String> urlPool;	
	private String startUrl;	
	private static boolean isWorking = true;
	private List<Thread> spiderPool;
	private List<Thread> parserPool;
	private static byte[] xorMaskIp;
	private static byte[] andMaskIp;
	@Autowired
	@Qualifier("dao")
	private BaseDAO dao;
	
	public String getStartUrl() {
		return startUrl;
	}

	public void setStartUrl(String startUrl) {
		this.startUrl = startUrl;
	}

	public void setXorMaskIp(byte[] xorMaskIp) {
		SpiderMan.xorMaskIp = xorMaskIp;
	}

	public void setAndMaskIp(byte[] andMaskIp) {
		SpiderMan.andMaskIp = andMaskIp;
	}

	public SpiderMan(){}
	
	public void startWorking(){
		loadStartUrlFromDb();
		if(urlPool.isEmpty()){
				urlPool.add(startUrl);
		}
		for(Thread s : spiderPool){
			new Thread(s).start();
		}
		for(Thread p : parserPool){
			new Thread(p).start();
		}	
		
			
	}

	private void loadStartUrlFromDb() {
		java.util.ArrayList<String> urlArray = dao.getStartUrl();
		for(String url : urlArray){
			urlPool.add(url);
		}
	}
	public void stopWorking(){
		isWorking = false;
	}
	
	public static boolean isWorking(){
		return isWorking;
	}
	
	public static boolean isIpAllowed(byte[] ip){
		ip[0]^=xorMaskIp[0];
		ip[0]&=andMaskIp[0];
		ip[1]^=xorMaskIp[1];
		ip[1]&=andMaskIp[1];
		ip[2]^=xorMaskIp[2];
		ip[2]&=andMaskIp[2];
		ip[3]^=xorMaskIp[3];
		ip[3]&=andMaskIp[3];
		
		return (ip[0]==0&&ip[1]==0&&ip[2]==0&&ip[3]==0);		
	}
	
	public void setUrlPool(Queue<String> urlPool) {
		this.urlPool = urlPool;
	}

	public static void setWorking(boolean isWorking) {
		SpiderMan.isWorking = isWorking;
	}


	public void setSpiderPool(List<Thread> spiderPool) {
		this.spiderPool = spiderPool;
	}

	public void setParserPool(List<Thread> parserPool) {
		this.parserPool = parserPool;
	}

	
}
